#include "ota_version.h"
#include "log/log.h"
#include <unistd.h>
#include "ota_http.h"
#include "cJSON/cJSON.h"
#include <openssl/sha.h>
#include <sys/reboot.h>
#include <string.h>
#include <stdlib.h>

static char *get_file_sha(char *filepath);
void ota_version_printVersion();

int ota_version_checkUpdate()
{
    // 1. 请求获取远程版本信息（json）
    char *json = ota_http_getJSON(OTA_URL_FILEINFO);
    if (!json)
    {
        log_error("Failed to get JSON");
        return -1;
    }
    
    // 2. 解析json得到各个版本号
    cJSON *root = cJSON_Parse(json);
    int major = cJSON_GetObjectItem(root,"major")->valueint;
    int minor = cJSON_GetObjectItem(root,"minor")->valueint;
    int patch = cJSON_GetObjectItem(root,"patch")->valueint;

    log_debug("Remote version: %d.%d.%d", major, minor, patch);
    ota_version_printVersion();

    // 3. 比较本地版本号和远程版本号
    if( VERSION_MAJOR > major || 
        ( VERSION_MAJOR == major && VERSION_MINOR > minor ) || 
        ( VERSION_MAJOR == major && VERSION_MINOR == minor && VERSION_PATCH > patch ) ||
        ( VERSION_MAJOR == major && VERSION_MINOR == minor && VERSION_PATCH == patch ) )
    {
        log_debug("当前版已是最新版本，无需更新");
        return 0;
    }
    // 4. 请求下载远程固件
    int ret = ota_http_download(OTA_URL_DOWNLOAD, OTA_LOCAL_FILE_PATH);
    if (ret != 0)
    {
        log_error("固件下载失败");
        return -1;
    }
    log_debug("固件下载成功");
    //5. 校验固件SHA1值
    char *remote_hash = cJSON_GetObjectItem(root,"sha1")->valuestring;
    log_debug("Remote hash: %s", remote_hash);
    char *local_hash = get_file_sha(OTA_LOCAL_FILE_PATH);
    log_debug("Local hash: %s", local_hash);
    if (strcmp(local_hash, remote_hash) != 0)
    {
        log_error("固件校验失败");
        free(local_hash);
        free(json);
        cJSON_Delete(root);
        unlink(OTA_LOCAL_FILE_PATH);//删除本地文件
        return -1;
    }
    // 7. 更新成功，释放资源，重启设备运行新固件
    free(local_hash);
    free(json);
    cJSON_Delete(root);

    // 重启设备
    reboot(RB_AUTOBOOT);

    return 0;
}

void ota_version_printVersion()
{
    log_debug("当前版本号：%d.%d.%d", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH);
}

void ota_version_checkUpdateDaily()
{
    while (1)
    {
        if (ota_version_checkUpdate() == -1)
        {
            log_error("固件更新失败");
        }
        sleep(24 * 60 * 60);
    }
}

/**
 * 获取文件的SHA1哈希值（40位16进制字符串）
 * 相同文件返回相同的哈希值，可用于判断文件是否相同
 * linux命令生成：sha1sum 文件名
 * 此函数可以利用AI工具帮我们生成
 */
static char *get_file_sha(char *filepath)
{
    FILE *file = fopen(filepath, "rb");
    if (!file)
    {
        perror("Failed to open file");
        return NULL;
    }

    unsigned char hash[SHA_DIGEST_LENGTH];
    SHA_CTX sha1;
    SHA1_Init(&sha1);

    const int bufSize = 32768;
    unsigned char *buffer = (unsigned char *)malloc(bufSize);
    if (!buffer)
    {
        perror("Failed to allocate memory");
        fclose(file);
        return NULL;
    }

    int bytesRead;
    while ((bytesRead = fread(buffer, 1, bufSize, file)) > 0)
    {
        SHA1_Update(&sha1, buffer, bytesRead);
    }

    SHA1_Final(hash, &sha1);
    fclose(file);
    free(buffer);

    char *outputBuffer = (char *)malloc(SHA_DIGEST_LENGTH * 2 + 1);
    if (!outputBuffer)
    {
        perror("Failed to allocate memory");
        return NULL;
    }

    for (int i = 0; i < SHA_DIGEST_LENGTH; i++)
    {
        sprintf(outputBuffer + (i * 2), "%02x", hash[i]);
    }

    return outputBuffer;
}